package com.lj.graduate.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lj.graduate.common.Constants;
import com.lj.graduate.common.Result;
import com.lj.graduate.controller.dto.UserDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lj.graduate.service.IUserService;
import com.lj.graduate.entity.User;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljy
 * @since 2023-03-23
 */
@RestController
@RequestMapping("/user")
        public class UserController {
    
@Resource
private IUserService userService;

// 新增或者更新
@PostMapping
public boolean save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
        }

@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
        }

@PostMapping("/del/batch")
public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return userService.removeByIds(ids);
        }

@GetMapping
public List<User> findAll() {
        return userService.list();
        }

@GetMapping("/{id}")
public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
        }

        @GetMapping("/page")
        public IPage<User> findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String userName,
                                    @RequestParam(defaultValue = "") String sex,
                                    @RequestParam(defaultValue = "") String address) {
                IPage<User> page = new Page<>(pageNum, pageSize);
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();

                if (!"".equals(userName)) {
                        queryWrapper.like("user_name", userName);
                }
                if (!"".equals(sex)) {
                        queryWrapper.like("sex", sex);
                }
                if (!"".equals(address)) {
                        queryWrapper.like("address", address);
                }
                return userService.page(page, queryWrapper);
        }
        /**
         * 导出接口
         */
        @GetMapping("/export")
        public void export(HttpServletResponse response) throws Exception {
                // 从数据库查询出所有的数据
                List<User> list = userService.list();
                // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
                // 在内存操作，写出到浏览器
                ExcelWriter writer = ExcelUtil.getWriter(true);
                //自定义标题别名
//                writer.addHeaderAlias("userId","用户id");
                writer.addHeaderAlias("userName", "用户名");
                writer.addHeaderAlias("birthday", "生日");
                writer.addHeaderAlias("tel", "电话");
                writer.addHeaderAlias("sex", "性别");
                writer.addHeaderAlias("address", "地址");
                writer.addHeaderAlias("credits", "积分");
                writer.addHeaderAlias("authority", "权限");
//                writer.addHeaderAlias("avatarUrl", "头像");
                writer.setOnlyAlias(true);
                        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
                writer.write(list, true);

                // 设置浏览器响应的格式
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
                String fileName = URLEncoder.encode("用户信息", "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

                ServletOutputStream out = response.getOutputStream();
                writer.flush(out, true);
                out.close();
                writer.close();

        }
        @PostMapping("/login")
        public Result login(@RequestBody UserDTO userDTO) {
                String tel = userDTO.getTel();
                String user_pwd = userDTO.getUser_pwd();
                if (StrUtil.isBlank(tel) || StrUtil.isBlank(user_pwd)) {
                        return Result.error(Constants.CODE_400,"参数错误");
                }
                UserDTO dto = userService.login(userDTO);
                return Result.success(dto);
        }
        @PostMapping("/register")
        public Result register(@RequestBody UserDTO userDTO){
                String tel = userDTO.getTel();
                String user_pwd = userDTO.getUser_pwd();
                if (StrUtil.isBlank(tel) || StrUtil.isBlank(user_pwd)) {
                        return Result.error(Constants.CODE_400,"参数错误");
                }
                return Result.success(userService.register(userDTO));
        }
        @GetMapping("/count")
        public long count(){
                return userService.count();
        }
        /**
         * excel 导入
         * @param file
         * @throws Exception
         */
//        @PostMapping("/import")
//        public Boolean imp(MultipartFile file) throws Exception {
//                InputStream inputStream = file.getInputStream();
//                ExcelReader reader = ExcelUtil.getReader(inputStream);
//                // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
////        List<User> list = reader.readAll(User.class);
//
//                // 方式2：忽略表头的中文，直接读取表的内容
//                List<List<Object>> list = reader.read(1);
//                List<User> users = CollUtil.newArrayList();
//                for (List<Object> row : list) {
//                        User user = new User();
//                        user.setUserName(row.get(0).toString());
//                        user.setTel(row.get(1).toString());
//                        user.setBirthday(LocalDate.parse(row.get(2).toString()));
//                        user.setSex(row.get(3).toString());
//                        user.setAuthority(row.get(4).toString());
//                        user.setAddress(row.get(5).toString());
//                        user.setUser_pwd(row.get(6).toString());
//                        users.add(user);
//                }
//
//                userService.saveBatch(users);
//                return true;
//        }
}

